package com.example.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.example.domain.DeptDBEntity;
import com.example.domain.EmailEntity;
import com.example.domain.common.Constants;
import com.example.mapper.DeptMapper;
import com.example.mapper.User2EmailMapper;
import com.example.service.EmailService;
import com.example.utils.MyCacheUtils;
import com.example.utils.PinyinUtils;
import com.example.utils.http.HttpsUtils;
import com.google.gson.Gson;

import lombok.extern.slf4j.Slf4j;

@Service
@Transactional
@Slf4j
public class EmailServiceImp implements EmailService {

	@Autowired
    private User2EmailMapper userMapper;
	@Autowired
    private DeptMapper deptMapper;
	/**
	 * 获取token信息
	 */
	@Override
	public String queryToken() {
		if(MyCacheUtils.get(Constants.EMAIL_TOKEN)==null) {
			log.info("重新调用接口获取token");
			return queryTokenByEmail();
		}else {
			log.info("缓存中存在,直接从缓存获取token");
			return MyCacheUtils.get(Constants.EMAIL_TOKEN).toString();
		}
	}

	/**
	 * 获取大华登录token,1.先调用接口获取公钥,2.在根据公钥获取token
	 */
	@Override
	public String queryTokenByEmail() {
		String bm = "utf-8";
		String getTokenUrl = "https://api.exmail.qq.com/cgi-bin/gettoken?"
				+ "corpid="+"wm163678b2574f3c31"
				+ "&corpsecret="+"BNG4cJTQSLQWZK3ynS0RSdbM2W6iEVKb2pgU43FZuX-jpeWlzb6LWiLq8b9ZahpB";
		String retMsg = HttpsUtils.doGet(getTokenUrl, bm);
		Map<String, Object> map = new HashMap<String, Object>();
		map = JSONObject.parseObject(retMsg);
		String token = map.get("access_token").toString();
		log.info("获取email token.url:{},\n return:{},\nmsg:{}",getTokenUrl,token,retMsg);
		int expires = Integer.parseInt(map.get("expires_in").toString())-5;// 过期时间（秒）
		if(expires<0) {
			expires = 0;
		}
		MyCacheUtils.put(Constants.EMAIL_TOKEN,token,expires*1000);//毫秒
		return token;
	}

	@Override
	public List<EmailEntity> queryAllUserByDB() {
		List<EmailEntity> list = userMapper.queryEmailPersonList();
		Gson gson = new Gson();
		String str = gson.toJson(list);
		System.out.println("用户:"+ str);
		for (EmailEntity emailEntity : list) {
			String name = emailEntity.getName();
			emailEntity.setUserid(PinyinUtils.getEmailName(name)+"@jinzhenghb.com");
		}
		return list;
	}

	@Override
	public List<EmailEntity> queryAllUserByEmail() {
		Map<String, String> deptMap = queryDeptMap();

		List<EmailEntity> retList = new ArrayList<EmailEntity>();

		String token = queryToken();
		String bm = "utf-8";
		String getEmailAllUserUrl = "https://api.exmail.qq.com/cgi-bin/user/list?"
				+ "access_token="+token+"&department_id=1&fetch_child=1";
		String retMsg = HttpsUtils.doGet(getEmailAllUserUrl, bm);

		Map<String, Object> map = new HashMap<String, Object>();
		map = JSONObject.parseObject(retMsg);
		String userlistStr = map.get("userlist").toString(); // .replaceAll("\\[", "").replaceAll("\\]", "")
		List<Object> u = JSONObject.parseArray(userlistStr);
		for (Object object : u) {
			EmailEntity emailEntity = JSONObject.parseObject(object.toString(),EmailEntity.class);
			String depts = emailEntity.getDepartment();
			List<String> deptNameList = new ArrayList<String>();
			List<Object> deptList = JSONObject.parseArray(depts);
			for (Object dept : deptList) {
				deptNameList.add(deptMap.get(dept.toString()));
			}
			String [] deptNameArray = deptNameList.toArray(new String[deptNameList.size()]);
			emailEntity.setDepartment(Arrays.toString(deptNameArray).replaceAll("\\[", "").replaceAll("\\]", ""));
			retList.add(emailEntity);
		}
		return retList;
	}
	@Override
	public EmailEntity queryOAPersonByWorkcode(String workcode){
		return userMapper.queryOAPersonByWorkcode(workcode);
	}
	@Override
	public Map<String, String> queryDeptMap() {
		Map<String, String> deptMap = new HashMap<String, String>();
		String token = queryToken();
		String bm = "utf-8";
		String getDeptListUrl = "https://api.exmail.qq.com/cgi-bin/department/list?"
				+ "access_token="+token;
		String retMsg = HttpsUtils.doGet(getDeptListUrl, bm);

		Map<String, Object> map = new HashMap<String, Object>();
		map = JSONObject.parseObject(retMsg);
		String department = map.get("department").toString(); // .replaceAll("\\[", "").replaceAll("\\]", "")
		List<Object> u = JSONObject.parseArray(department);
		for (Object object : u) {
			map = JSONObject.parseObject(object.toString());
			String deptId = map.get("id").toString();
			String deptName = map.get("name").toString();
			deptMap.put(deptId, deptName);
		}
		return deptMap;
	}

	@Override
	public List<EmailEntity> test() {
		StringBuffer names = new StringBuffer();
		StringBuffer namesSB = new StringBuffer();
		List<EmailEntity> dbList = queryAllUserByDB();
		List<EmailEntity> emailList = queryAllUserByEmail();
		for (EmailEntity emailEntity : emailList) {
			String name = emailEntity.getName();
			boolean boo = true;
			StringBuffer sb = new StringBuffer();
			for (EmailEntity db : dbList) {
				if(db.getName().equals(name)) {
					sb.append(db.getExtid()).append(",");
					boo = false;
				}
			}
			if(boo) {
				names.append(name).append("_").append(emailEntity.getDepartment()).append(",");
			}else {
				String loginids = sb.toString();
				loginids = loginids.substring(0,loginids.length()-1);
//				System.out.println("id:"+emailEntity+",name:"+name+",email:"+emailEntity.getUserid()+",找到相同名称,id:"+loginids);
				if(loginids.contains(",")) {
					namesSB.append(name).append("_").append(emailEntity.getDepartment()).append(",");
				}else {
					if("姜飞".equals(name)) {
//						updateUserExtid(emailEntity.getUserid(),loginids);
					}
				}
				emailEntity.setExtid(loginids);
			}
		}
		System.out.println("name:"+names.toString()+"在泛微未找到相同名称");
		System.out.println("name:"+namesSB.toString()+"在泛微未找到多个相同名称");

		List<DeptDBEntity> deptListDB = getDeptTreeList();
		Map<String, String> deptNameIdMap = queryDeptMapNameId();
		List<DeptDBEntity> setEmailIdDeptList = setDeptEmailId(deptListDB,deptNameIdMap,"0");
		log.info("赋值企业邮箱id后:\n{}",JSONObject.toJSONString(setEmailIdDeptList));
		return emailList;
	}

	private void updateUserExtid(String userid,String extid) {
		String token = queryToken();
		String bm = "utf-8";
		String updateUserUrl = "https://api.exmail.qq.com/cgi-bin/user/update?access_token="+token;
		String param = "{\"userid\":\""+userid+"\",\"extid\":\""+extid+"\"}";
		String retMsg = HttpsUtils.doPost(updateUserUrl, param, bm);
		log.info("updateUserExtid.url:{},param:{},\n return:{}", updateUserUrl, param, retMsg);
	}

	/**
	 * 获取泛微整个部门的树状结构
	 * @return
	 */
	public List<DeptDBEntity> getDeptTreeList() {
		List<DeptDBEntity> companyListDB = deptMapper.queryCompanyList();
		List<DeptDBEntity> subcompanyListDB = deptMapper.querySubcompanyList();
		for (DeptDBEntity company : companyListDB) {
			for (DeptDBEntity subcompany : company.getSunDept()) {
				for (DeptDBEntity subcompanyDB : subcompanyListDB) {
					if(subcompany.getDeptId().equals(subcompanyDB.getDeptId())) {
						List<DeptDBEntity> sunDeptListDB = subcompanyDB.getSunDept();
						for (DeptDBEntity deptDBEntity : sunDeptListDB) {
							queryDept(deptDBEntity);
						}
						subcompany.setSunDept(sunDeptListDB);
					}
				}
			}
		}
//		log.info("getDeptTreeList:\n{}",JSONObject.toJSONString(companyListDB));
		return companyListDB;
	}

	/**
	 * 递归获取当前部门下的所有子部门
	 * @param pDept 当前部门
	 * @return 部门
	 */
	private DeptDBEntity queryDept(DeptDBEntity pDept) {
		List<DeptDBEntity> sunDeptListDB = deptMapper.queryDeptListByPid(pDept.getDeptId());
		if(sunDeptListDB!=null && sunDeptListDB.size()>0) {
			for (DeptDBEntity deptDBEntity : sunDeptListDB) {
				queryDept(deptDBEntity);
			}
			pDept.setSunDept(sunDeptListDB);
		}
		return pDept;
	}
	/**
	 * 获取企业邮箱map key:名称 value:id
	 * @return
	 */
	private Map<String, String> queryDeptMapNameId() {
		Map<String, String> deptMap = new HashMap<String, String>();
		String token = queryToken();
		String bm = "utf-8";
		String getDeptListUrl = "https://api.exmail.qq.com/cgi-bin/department/list?"
				+ "access_token="+token;
		String retMsg = HttpsUtils.doGet(getDeptListUrl, bm);

		Map<String, Object> map = new HashMap<String, Object>();
		map = JSONObject.parseObject(retMsg);
		String department = map.get("department").toString(); // .replaceAll("\\[", "").replaceAll("\\]", "")
		List<Object> u = JSONObject.parseArray(department);
		for (Object object : u) {
			map = JSONObject.parseObject(object.toString());
			String deptId = map.get("id").toString();
			String deptName = map.get("name").toString();
			deptMap.put(deptName, deptId);
		}
		return deptMap;
	}

	/**
	 * 递归赋值泛微的部门 企业邮箱对应的id
	 * @param pDept 当前部门
	 * @return 部门
	 */
	private List<DeptDBEntity> setDeptEmailId(List<DeptDBEntity> deptlist,Map<String, String> deptMap,String pid) {
		for (DeptDBEntity deptDBEntity : deptlist) {
			deptDBEntity.setPIdInEmail(pid);
			deptDBEntity.setDeptIdInEmail(deptMap.get(deptDBEntity.getDeptName()));
			List<DeptDBEntity> sunDeptListDB = deptDBEntity.getSunDept();
			if(sunDeptListDB!=null && sunDeptListDB.size()>0) {
				setDeptEmailId(sunDeptListDB,deptMap,deptDBEntity.getDeptIdInEmail());
			}
		}
		return deptlist;
	}


	/**
	 * 获取组织架构
	 * auth
	 * @return
	 */
	public List<EmailEntity> test2() {
		StringBuffer names = new StringBuffer();
		StringBuffer namesSB = new StringBuffer();
		List<EmailEntity> dbList = queryAllUserByDB();

//		List<EmailEntity> emailList = queryAllUserByEmail();
//		for (EmailEntity emailEntity : emailList) {
//			String name = emailEntity.getName();
//			boolean boo = true;
//			StringBuffer sb = new StringBuffer();
//			for (EmailEntity db : dbList) {
//				if(db.getName().equals(name)) {
//					sb.append(db.getExtid()).append(",");
//					boo = false;
//				}
//			}
//			if(boo) {
//				names.append(name).append("_").append(emailEntity.getDepartment()).append(",");
//			}else {
//				String loginids = sb.toString();
//				loginids = loginids.substring(0,loginids.length()-1);
////				System.out.println("id:"+emailEntity+",name:"+name+",email:"+emailEntity.getUserid()+",找到相同名称,id:"+loginids);
//				if(loginids.contains(",")) {
//					namesSB.append(name).append("_").append(emailEntity.getDepartment()).append(",");
//				}else {
//					if("姜飞".equals(name)) {
////						updateUserExtid(emailEntity.getUserid(),loginids);
//					}
//				}
//				emailEntity.setExtid(loginids);
//			}
//		}
//		System.out.println("name:"+names.toString()+"在泛微未找到相同名称");
//		System.out.println("name:"+namesSB.toString()+"在泛微未找到多个相同名称");

		List<DeptDBEntity> deptListDB = getDeptTreeList();
		log.info("组织{}",deptListDB);
		return null;
	}

	public static void main(String[] args) {
		String string = "     ValidationError\r\n"
				+ "	  CellClick     \r\n"
				+ "	  CellDoubleClick        \r\n"
				+ "	  EnterCell         \r\n"
				+ "	  LeaveCell        \r\n"
				+ "	  ValueChanged          \r\n"
				+ "	  TopRowChanged        \r\n"
				+ "      LeftColumnChanged         \r\n"
				+ "	  InvalidOperation          \r\n"
				+ "	  RangeFiltering         \r\n"
				+ "	  RangeFiltered          \r\n"
				+ "	  TableFiltering         \r\n"
				+ "      TableFiltered         \r\n"
				+ "	  RangeSorting          \r\n"
				+ "	  RangeSorted         \r\n"
				+ "      ClipboardChanging         \r\n"
				+ "	  ClipboardChanged         \r\n"
				+ "	  ClipboardPasting          \r\n"
				+ "      ClipboardPasted         \r\n"
				+ "	  ColumnWidthChanging          \r\n"
				+ "	  ColumnWidthChanged          \r\n"
				+ "	  RowHeightChanging          \r\n"
				+ "	  RowHeightChanged         \r\n"
				+ "	  DragDropBlock          \r\n"
				+ "	  DragDropBlockCompleted    \r\n"
				+ "	  DragFillBlock         \r\n"
				+ "	  DragFillBlockCompleted        \r\n"
				+ "	  EditStarting          \r\n"
				+ "	  EditStarted         \r\n"
				+ "      EditChange          \r\n"
				+ "      EditEnding        \r\n"
				+ "	  EditEnd         \r\n"
				+ "      EditEnded         \r\n"
				+ "	  RangeGroupStateChanging       \r\n"
				+ "	  RangeGroupStateChanged         \r\n"
				+ "	  SelectionChanging         \r\n"
				+ "	  SelectionChanged        \r\n"
				+ "	  SheetTabClick         \r\n"
				+ "	  SheetTabDoubleClick      \r\n"
				+ "      SheetNameChanging        \r\n"
				+ "	  SheetNameChanged         \r\n"
				+ "	  UserZooming         \r\n"
				+ "	  UserFormulaEntered        \r\n"
				+ "	  CellChanged          \r\n"
				+ "	  Changed         \r\n"
				+ "      SparklineChanged         \r\n"
				+ "	  RangeChanged         \r\n"
				+ "	  ButtonClicked          \r\n"
				+ "	  EditorStatusChanged        \r\n"
				+ "	  FloatingObjectChanged          \r\n"
				+ "	  FloatingObjectSelectionChanged      \r\n"
				+ "	  PictureChanged         \r\n"
				+ "	  FloatingObjectRemoving         \r\n"
				+ "	  FloatingObjectRemoved         \r\n"
				+ "	  PictureSelectionChanged        \r\n"
				+ "	  FloatingObjectLoaded         \r\n"
				+ "	  TouchToolStripOpening          \r\n"
				+ "	  CommentChanged          \r\n"
				+ "	  CommentRemoving         \r\n"
				+ "	  CommentRemoved          \r\n"
				+ "	  SlicerChanged         \r\n"
				+ "	  ResetBinding        \r\n"
				+ "	  InitBinding         \r\n"
				+ "	  BeforeDragDrop         \r\n"
				+ "	  FormulatextboxActiveSheetChanging        \r\n"
				+ "	  FormulatextboxActiveSheetChanged         \r\n"
				+ "	  FormulatextboxEditStarted         \r\n"
				+ "	  FormulatextboxEnterCell         \r\n"
				+ "	  FormulatextboxEditEnded        \r\n"
				+ "	  FormulatextboxRangeChanged         \r\n"
				+ "	  SheetMoving         \r\n"
				+ "	  SheetMoved         \r\n"
				+ "      DragMerging         \r\n"
				+ "	  DragMerged         \r\n"
				+ "      ChartClicked         \r\n"
				+ "	  BeforePrint        \r\n"
				+ "	  FormulaTextBoxTextChanged         \r\n"
				+ "      FormulaTextBoxCaretChanged    \r\n"
				+ "	  ";
		string.split("");




	}
}

